package com.orange.core.security.token;

import com.orange.core.security.detail.AdminDetail;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
public class AdminPersistenceToken implements Serializable {

    private AdminDetail principal;
    private String credentials;
    private Boolean rememberMe;
    private Boolean authenticated;

    public static AdminPersistenceToken of(AdminAuthenticationToken token) {
        if (token.getPrincipal() instanceof AdminDetail principal) {
            AdminPersistenceToken persistenceToken = new AdminPersistenceToken();
            AdminDetail persistencePrincipal = new AdminDetail(principal.getId(), principal.getUsername(), principal.getPassword(), new ArrayList<>())
                    .setToken(principal.getToken()).setRoles(principal.getRoles()).setPermissions(principal.getPermissions());
            persistenceToken.setPrincipal(persistencePrincipal);
            persistenceToken.setCredentials((String) token.getCredentials());
            persistenceToken.setRememberMe(token.getRememberMe());
            persistenceToken.setAuthenticated(token.isAuthenticated());
            return persistenceToken;
        } else {
            throw new RuntimeException("token未认证");
        }
    }

    public Authentication toAuthenticationToken() {
        List<GrantedAuthority> authorities = principal.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        authorities.addAll(principal.getPermissions().stream().map(SimpleGrantedAuthority::new).toList());
        return new AdminAuthenticationToken(principal, credentials, rememberMe, authorities);
    }
}
